<?php
require 'TVB/pms/pdes/common/util/UpdateMeta.class.php';
require 'TVB/ImageInfrastructure/Client/requires.php';
require_once('TVB/pms/pdes/action/ImageGetAction.class.php');
require_once 'TVB/pms/pdes/model/cast_dictionary.php';

class ImageUpdateAction extends BaseAction 
{
    public $id;
    public $title;
    public $onair_episode_no;
	/**
	 * @filter datetime
	 * @label Online Date Time
	 */
    public $online_date_time;
	/**
	 * @filter datetime
	 * @label Offline Date Time
	 */
    public $offline_date_time;
    public $country_allow_deny;
    public $country;
	public $modified_at;
    public $copyright;
    public $copyright_owner;
    public $mdes_status;
    public $langid;
    public $episode_id;
    public $edit_eps;
	public $reset;
	public $from;
    public $cast_dict_id;
    public $tag;
    public $new_tag;
    public $tags;
	public $ut;
    
    public function execute()
    {
		if (!is_null($this->reset)) {
			$this->setData('id', $this->id);
			$this->setData('type', 'image');
			$this->setData('act', 'edit');
			$this->setData('from', $this->from);
			return 'reset';
		}

		Model::$dbo['w']->beginTransaction();
        try {
            if (count($this->_errors) > 0) {
				$this->init_page_data();
				return 'filter-error';
			}

			if ($this->check_concurrent() && $this->ut==FALSE) {
				$this->addError('concurrent', array('0105', 'Concurrent update found!'));
				$this->init_page_data();
				return 'logic-error';
			}

			if (!empty($this->online_date_time) && !empty($this->offline_date_time)) {
				if ($this->online_date_time > $this->offline_date_time) {
					$this->addError('Online Date Time && Offline Date Time', array('0032', 'Online Date Time && Offline Date Time'));
					$this->init_page_data();
					return 'filter-error';
				}
			}

			$this->langid = language::getLanguageID(AC::DEFAULT_LANGUAGE);
			$result = $this->update_image();
			if(!$result){
				$this->init_page_data();
				return 'logic-error';
			}

			$this->setData("type", "image");
			$meta_obj = new UpdateMeta('Image', $this->id);
			$meta_obj->UpdateAcl();
			$meta_obj->UpdateMeta('Programme');

			Model::$dbo['w']->commit();

            if ($this->edit_eps && $this->episode_id) {
                $this->setData('act', 'edit');
                $this->setData('step', 2);
                $this->setData('id', $this->episode_id);
                return 'episode';
            } else {
			    return ($this->from == 'task') ? 'task' : 'succ';
            }
		} catch(Exception $e) {
			error_log("Update Image Fails: $this->id");
			error_log("Request: " . var_export($this, 1));

			Model::$dbo['w']->rollBack();

			return 'system-error';
		}
	}

    private function update_image()
    {
        $image = new image();
        $image = $image->get($this->id);
        Model::diff($image, $this);
        $image->publish_datetime = $this->online_date_time;
        $image->expire_datetime = $this->offline_date_time;
        $image->modified_at = date("Y-m-d H:i:s");
        $image->modified_by = CommonUtils::get_user();

        if (is_array($this->cast_dict_id)) {
            array_unique($this->cast_dict_id);
            $image->casts = implode(',', $this->cast_dict_id); 
        } else {
            $image->casts = '';
        }

        $image->tags = $this->get_tags();

        if ($this->onair_episode_no) {
            $image->episode_id = episode::getEpisodeId($image->programme_id, $this->onair_episode_no);
            if (!$image->episode_id) {
                $this->addError('On Air Episode Number Error', array('0057', "On Air Episode Number Error")); 
                return false;
            } else {
                $this->episode_id = $image->episode_id;
            }
        } else {
            $this->episode_id = $image->episode_id = 0;
        }

        if (strtoupper($image->copyright) <> 'TVB') {
            $image->copyright = $this->copyright_owner;
        }

        if ('allow' ==  $this->country_allow_deny)
        {
            $image->country_allow_list  =   is_null($this->country) ? '' : ParseCountryCode::json2country($this->country); 
            $image->country_deny_list   =   'ALL';
        }
        else
        {
            $image->country_allow_list  =   'ALL';
            $image->country_deny_list  =   is_null($this->country) ? '' : ParseCountryCode::json2country($this->country); 
        }

		$update_id = Model::$dbo['w']->save($image);
		if ($update_id > 0) {
			$image->add_change_log();

			$result = ChangeLogTools::getEpisodeIdsByImageId($image->id);
			folder_item::addFolderItemChangeLog('image', $image->id, $result['programme_id'], $result['episode_id'], 1);
			$this->update_image_language($image->programme_id, $image->episode_id);
			$this->addInfo("image:".AC::LOG_OP_UPDATE.":".$this->id, "update image success", json_encode($image));
			return true;
		} else {
			$this->addError("image:".AC::LOG_OP_UPDATE.":".$this->id, "update image failed", json_encode($image));
			return false;
		}
    }

    private function update_image_language($programme_id, $episode_id)
    {
        $image_language = Model::$dbo['w']->find('image_language','image_id=? and language_id=?',
                                                 array($this->id, $this->langid));
        $image_language[0]->title = trim($this->title);
        Model::$dbo['w']->save_by_fields($image_language[0], array('image_id', 'language_id'));

		$image_language[0]->add_change_log();
    }

	private function get_tags(){
		$all_tags = array();
		if(isset($this->tag[1])){
			$sql = 'SELECT id  FROM tag t where system_label = :label and tag_type_id =1';
			foreach($this->tag[1] as $tag){

				if(is_array($tag)){
					$t_id = Model::selectBySql($sql,array(':label'=>urldecode(trim($tag['new']))));
					if(empty($t_id))
					{
						$tag_obj = new tag();
						$tag_obj->parent_id = 0;
						$tag_obj->tag_type_id = 1;
						$tag_obj->system_label = urldecode(trim($tag['new']));
						$tag_obj->id = $tag_id = Model::$dbo['w']->save($tag_obj);
						$tag_obj->add_change_log();
						$all_tags[] = $tag_id;
					}
					else
					{
						$tid = $t_id[0]['id'];
						$all_tags[] = tag::IsParent($tid);
					}
				}
				else
				{
					$all_tags[] = tag::IsParent($tag);
				}
			}
		}
        return empty($all_tags) ? '' : implode(',', array_unique($all_tags));
	}

	private function init_page_data()
	{
		$action = new ImageGetAction();
		$action->id = $this->id;
		$action->act = 'edit';
		$action->execute();

		$old_data = $action->getData();
        $old_data['image']['mdes_status'] = $this->mdes_status;
		$old_data['image']['title'] = $this->title;
        $old_data['image']['copyright'] = $this->copyright=='TVB' ? 'TVB' : $this->copyright_owner;
        $old_data['image']['onair_episode_no'] = $this->onair_episode_no;
        if (!empty($this->cast_dict_id)) {
            $old_data['image']['casts'] = cast_dictionary::getCastListById($this->cast_dict_id); 
        }

		if (is_array($this->online_date_time)) {
			$old_data['image']['publish_datetime'] = implode(' ', $this->online_date_time);
			$old_data['image']['publish_datetime'] = CommonUtils::formatDate($old_data['image']['publish_datetime']);
		} else {
			$old_data['image']['publish_datetime'] = CommonUtils::formatDate($this->online_date_time);
		}

		if (is_array($this->offline_date_time)) {
			$old_data['image']['expire_datetime'] = implode(' ', $this->offline_date_time);
			$old_data['image']['expire_datetime'] = CommonUtils::formatDate($old_data['image']['expire_datetime']);
		} else {
			$old_data['image']['expire_datetime'] = CommonUtils::formatDate($this->offline_date_time);
		}

        if ('allow' ==  $this->country_allow_deny) {
            $old_data['image']['global_country_allow_deny'] = 0; 
            $old_data['image']['global_country']   =   is_null($this->country) ? "" :  $this->country;
        } else {
            $old_data['image']['global_country_allow_deny'] = 1; 
            $old_data['image']['global_country']   =   is_null($this->country) ? "" :  $this->country;
        }
		
		$tag_arr = array();
        if(isset($this->tag[1]))
        {
            foreach ($this->tag[1] as $value)
            {
                if(is_array($value)) 
                {
                    $value = $value['new'];
                    $tag_arr[1][] = array('is_new'=>1,'system_label'=>urldecode(trim($value)), 'id'=>$value);
                }
                else
                {
                    $tag = new tag();
                    $tag_detail = $tag->get($value);
                    $tag_arr[1][] = array(
                        'system_label'	=> urldecode($tag_detail->system_label), 
                        'id'			=> $value
                    );
                }
            }
        }
        $old_data['image']['init_tag'] = $tag_arr;

		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
		}

		//jump page
		$this->setData('id', $this->id);
		$this->setData('type', 'image');
		$this->setData('act', 'edit');
		$this->setData('from', $this->from);
	}

	/*
	 * concurrent handle
	 */
	private function check_concurrent()
	{
		$image = new image();
		$image_detail = $image->get($this->id);

		if ($image_detail->modified_at == $this->modified_at) {
			return false;
		} else {
			return true;
		}
	}
}
?>
